package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.UserDao;
import com.lilicould.entity.ChangePasswordRequest;
import com.lilicould.entity.Users;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.mindrot.jbcrypt.BCrypt;


public class LoginService {
    public Users login(String user_no, String password,String role) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            // 调用方法获取用户信息
            Users user = userDao.getUserByUserNo(user_no);
            if (user != null && BCrypt.checkpw(password, user.getPassword()) && user.getRole().equals(role))
                return user;
            return null;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public String changePassword(ChangePasswordRequest cpr) {
        Gson gson = new Gson();
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            UserDao userDao = sqlSession.getMapper(UserDao.class);

            // 获取用户信息
            Users user = userDao.getUserByUserNo(cpr.getUserNo());
            // 验证旧密码
            if (user != null && BCrypt.checkpw(cpr.getOldPassword(), user.getPassword())) {
                // 旧密码正确，修改密码为新密码
                user.setPassword(BCrypt.hashpw(cpr.getNewPassword(), BCrypt.gensalt()));
                // 将修改后的用户信息保存到数据库
                int result = userDao.updateUser(user);
                if (result > 0) {
                    // 修改成功，提交事务
                    sqlSession.commit();
                    return null;
                } else {
                    // 修改失败，返回错误信息
                    return gson.toJson("更新密码失败");
                }
            }else {
                return gson.toJson("旧密码错误");
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
